import { Button, Card, WingBlank, WhiteSpace, List, Badge, Modal, Brief, Toast } from 'antd-mobile';
import React, { Component } from 'react';
import { View, AppRegistry, ScrollView, Text, Image, FlatList } from 'react-native';
import { Urls } from '../../utils/Urls';
const more = false;
const pageNumber = 1;

import { NavigationActions } from 'react-navigation'
const loginAction = NavigationActions.reset({
    index: 0,
    actions: [
        NavigationActions.navigate({ routeName: 'LoginScreen', params: { token: '123456' } })
    ]
})
export class AlarmListScreen extends Component {
    static navigationOptions = {
        tabBarLabel: '警报',
        tabBarIcon: ({ tintColor }) => (
            <Image
                source={require('../../assets/Images/alarm.png')}
                style={{ width: 25, height: 25 }}
            />
        ),
        headerTitle: '警报',
        headerTitleStyle: { alignSelf: 'center' }
    };
    constructor(props) {
        super(props)
    }
    state = {
        alarmList: [],
        modal1: false,
        refreshing: true,
        more: true,
        detail: {
            temperature: '',
            name: '',
            num: '',
            create_time: ''
        }
    }
    getData = () => {
        
        let url = Urls.PUSH_LIST + `?pageNumber=${pageNumber}&stationId=${this.props.navigation.state.params.id}`;
        let $this = this;
        fetch(url)
            .then((response) => {
                console.log(response)
                var responsejson = JSON.parse(response._bodyInit);
                // 如果正确返回并且当前页是最后一页，那么不再请求
                if (responsejson.code == 1) {
                    Toast.fail('登录过期，重新登录', 1);
                    $this.props.navigation.dispatch(loginAction)
                    return;
                }
                
                if (responsejson.code == 0 && responsejson.content.totalPage > responsejson.content.pageNumber) {
                    more = true
                }
                pageNumber = responsejson.content.pageNumber;
                this.setState({
                    alarmList: responsejson.content.list,
                    refreshing: false
                })
            })
            .catch((error) => {
                console.log(error);
            })
    }
    componentDidMount() {
        this.getData();
    }
    showModal = (key, index) => (e) => {
        console.log("弹出对话框" + key + ":" + [key])
        
        this.state.alarmList[index].status = 1
        this.setState({
            [key]: true,
            detail: {
                temperature: this.state.alarmList[index].temperature,
                name: this.state.alarmList[index].name,
                num: this.state.alarmList[index].num,
                create_time: this.state.alarmList[index].create_time
            }
        });
        
        fetch(Urls.pushStatusChange + "?pushId=" + this.state.alarmList[index].id)
        .then(response => response.json());
        
        e.preventDefault();
    }
    onClose = key => () => {
        this.setState({
            [key]: false,
        });
    }

    render() {
        const { navigate } = this.props.navigation.state.params.id;
        return (
            <View>
                <Modal
                    visible={this.state.modal1}
                    transparent={true}
                    animationType='slide'
                    maskClosable={false}
                    onClose={this.onClose('modal1')}
                    title="警报信息"
                    footer={[{ text: '我知道了', onPress: () => { console.log('ok'); this.onClose('modal1')(); } }]}
                    wrapProps={{ onTouchStart: this.onWrapTouchStart }}
                >
                    <View>
                        <List>
                            <List.Item style={{ flexDirection: 'row' }}>
                                <Image source={require('../../images/alarm.png')} style={{ alignSelf: 'center', marginTop: 5 }} />
                            </List.Item>
                            <List.Item extra={this.state.detail.temperature + '℃'}>
                                {this.state.detail.name}
                            </List.Item>
                        </List>
                        <WhiteSpace size="lg" />
                        <List>
                            <List.Item style={{ flexDirection: 'row' }}><Text>探头编号：{this.state.detail.num}</Text></List.Item>
                            <List.Item style={{ flexDirection: 'row' }}><Text>时间：{this.state.detail.create_time}</Text></List.Item>
                            
                        </List>
                    </View>
                </Modal>
                <WhiteSpace />
                <FlatList
                    data={this.state.alarmList}
                    renderItem={({ item, index }) => 
                    <List.Item key={index} onClick={this.showModal('modal1', index)} extra={item.temperature + "℃"} multipleLine>
                            {item.name}
                            { item.status==0 ?
                                <Badge dot>
                                    <Text>{item.create_time}</Text>
                                </Badge>
                                :
                                <Text>{item.create_time} </Text>
                            }
                            <WhiteSpace/>
                            {/* <Card full>
                                <Card.Header title={item.equipment} extra={item.temperature + '℃'} />
                                <Card.Footer content={item.create_time} extra={item.station} />
                            </Card> */}
                        </List.Item>
                    }
                    onRefresh={this._onRefresh}
                    refreshing={false}
                    // onEndReached={this._onEndReached}
                    ListFooterComponent={this._footer} //添加尾部组件
                    ListEmptyComponent={this.createEmptyView()}
                    keyExtractor={(item, index) => index}
                    // getItemLayout={(data, index) => ({
                    //     length: 208, offset: 208 * index, index
                    // })}
                />
                <WhiteSpace size="lg" />
            </View>
        );
    }
    //ES6的写法
    _footer = () => (
        <Text style={{ fontSize: 14, alignSelf: 'center' }}>到底啦，没有啦！</Text>
    )
    createEmptyView() {
        return (
            <Text style={{ fontSize: 40, alignSelf: 'center' }}>还没有数据哦！</Text>
        );
    }
    _onRefresh = () => this.getData();
    _onEndReached = () => {
        // this.setState((state) => ({
        //   data: state.data.concat(genItemData(100, state.data.length)),
        // }));
        if (!more) {
            return;
        }
        let url = Urls.PUSH_LIST + `?pageNumber=${pageNumber+1}&stationId=${this.props.navigation.state.params.id}`;
        this.setState({
            refreshing: true
        })
        fetch(url)
            .then((response) => {
                console.log(response)
                var responsejson = JSON.parse(response._bodyInit);
                this.setState({
                    alarmList: this.state.alarmList.concat(responsejson.content.list),
                    refreshing: false
                })
            })
            .catch((error) => {
                console.log(error);
            })
        console.log("到底部了")
    };
}